﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WebSocket4Net;

namespace Chat
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Window
    {
        private delegate void CloseW();
        public WebSocket webSocket;
        string host;
        public string pwd;
        public long id;

        private void CloseWindow()
        {
            if (this.Dispatcher.Thread != Thread.CurrentThread)
            {
                this.Dispatcher.Invoke(new CloseW(CloseWindow));
            }
            else
            {
                Close();
            }
        }

        public void AutoReconnectWebSocket(object sender, EventArgs e)
        {
            
            if (host == Resource1.ServerHostV6)
            {
                host = Resource1.ServerHost;
            }
#if DEBUG
            host = Resource1.DebugHost;
#endif
            webSocket = new WebSocket(host);
            webSocket.Open();
            webSocket.Closed += AutoReconnectWebSocket;
            webSocket.MessageReceived += ProcessWS;
            webSocket.MessageReceived += Method.ErrorProcessor;
        }

        public Login(string host)
        {
            InitializeComponent();
            Height = Math.Max(SystemParameters.PrimaryScreenHeight / 2.5, 400);
            Width = SystemParameters.PrimaryScreenWidth / 4;

            this.SizeChanged += new System.Windows.SizeChangedEventHandler(ResizeWin);
            this.Header.MouseLeftButtonDown += (o, e) => { DragMove(); };

            webSocket = new WebSocket(host);
            webSocket.Open();
            webSocket.Closed += AutoReconnectWebSocket;
            webSocket.MessageReceived += ProcessWS;
            webSocket.MessageReceived += Method.ErrorProcessor;
            this.host = host;
            if (File.Exists("UserData"))
            {
                RememberPwd.IsChecked = true;
                string[]fs = File.ReadAllLines("UserData");
                uid.Text = fs[0];
                password.Password = fs[1].Substring(12);
            }
        }

        private void ResizeWin(object sender, System.EventArgs e)
        {
            if (this.Width / 40 < 16)
            {
                ToReg.FontSize = this.Width / 40;
                RememberPwd.FontSize = this.Width / 30;
                InvisibleLog.FontSize = this.Width / 30;
            }
        }

        private void ProcessWS(object sender, MessageReceivedEventArgs e)
        {
            if (e.Message == "Login\nSuccess\n\n")
            {
                webSocket.MessageReceived -= ProcessWS;
                webSocket.Closed -= AutoReconnectWebSocket;
                MessageBox.Show("登陆成功");
                CloseWindow();
            }
        }

        private void LoginButtonClick(object sender, RoutedEventArgs e)
        {
            if (RememberPwd.IsChecked ?? false){
#if DEBUG
                File.WriteAllText("UserData", uid.Text + '\n' + "{#hadSHA512}" + (password.Password));
#else
                File.WriteAllText("UserData", uid.Text + '\n' + "{#hadSHA512}" + Protocol.sha512Encode(password.Text));
#endif
            }
            else
            {
                if (File.Exists("UserData"))
                {
                    File.Delete("UserData");
                }
            }

            string Password;

            if (password.Password.IndexOf("{#hadSHA512}") != -1)
            {
                Password = password.Password.Replace("{#hadSHA512}", "");
            }
            else
            {
#if DEBUG
                Password = password.Password;
#else
                Password = Protocol.sha512Encode(password.Text);
#endif
            }
            pwd = Password;
            if (webSocket.State != WebSocketState.Open)
            {
                ErrorLabel.Visibility = Visibility.Visible;
                ErrorLabel.Content = "未连接服务器";
                ErrorLabel.Background = new SolidColorBrush(Color.FromRgb(255, 255, 0));
                return;
            }
            id = Convert.ToInt64(uid.Text);
            webSocket.Send(string.Format("Login\n{0}\n{1}\n\n", uid.Text, Password));
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Method.LogoutExit(webSocket);
        }

        private void Reg_Click(object sender, RoutedEventArgs e)
        {
            Hide();
            Register register = new Register(host);
            register.ShowDialog();
            if (register.id != 0)
            {
                id = register.id;
                webSocket = register.webSocket;
                CloseWindow();
            }
            else
            {
                try
                {
                    ShowDialog();
                }
                catch { Method.LogoutExit(webSocket); }
            }
        }
    }
}
